package com.bilibili.myblogbackend.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Bean/*配置：登录放行*/
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        /*关闭csrf*/
        http.csrf(csrf->csrf.disable());
        /*配置请求拦截方式*/
     /*   http.authorizeHttpRequests(auth->
                auth.requestMatchers("user/login")
                        .permitAll()
                        .anyRequest()
                        .authenticated());*/


        http.authorizeHttpRequests(auth ->
                auth.requestMatchers("/comment/*").authenticated()
                        .anyRequest().permitAll());
//        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
        /*将我们自定义的jwtfilter放在UsernamePasswordAuthenticationFilter（因为他是整个security框架，锅炉气链最开始那个过滤器）之前*/

        //用户认证（token）失败处理器配置
//        http.formLogin(login->login.failureHandler(authenticationFailureHandler));


    /*    http.exceptionHandling(handler->
                handler.accessDeniedHandler(noAuthorityHandler)*//*配置当用户请求没有权限时的响应(配置响应类)*//*
                        .authenticationEntryPoint(failedLoginHandler)*//*配置用户登录异常响应*//*

        );*/



        return http.build();
    }

    @Bean
      /* 这个AuthenticationManager类的authenticate方法是用于对前端传过来的username和password封装成
       UsernamePasswordAuthenticationToken对象进行身份校验的
       * 成功就返回UserDetails对象，否则抛异常
       * */
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
}
